package cn.house.rent.controller;

import cn.house.rent.entity.User;
import cn.house.rent.service.UserService;
import cn.house.rent.utils.Result;
import cn.house.rent.vo.UserVo;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //用户登录
    @RequestMapping("login")
    public Object login(UserVo userVo, HttpServletResponse resp, HttpSession session) {
        Result login = userService.login(userVo,resp,session);
        return login;
    }

    //退出登录
    @RequestMapping("loginOut")
    public Object loginOut(HttpSession session) {
        session.removeAttribute("user");
        return Result.builder().code(0).msg("退出成功！").build();
    }

    //检测用户账号是否重复
    @RequestMapping("registerCheck")
    public Object registerCheck(String userName) {
        return userService.registerCheck(userName);
    }

    //检测邮箱账号是否重复
    @RequestMapping("emailCheck")
    public Object emailCheck(String email, HttpSession session) {
        Result result = userService.emailCheck(email);
        session.setAttribute("emailCode", result.getCode());
        return result;
    }

    //注册用户
    @RequestMapping("register")
    public Object register(User user, @RequestParam("captcha") String captcha, HttpSession session) {
        return userService.register(user, captcha, session);
    }

    //向接收的邮箱发送验证码
    @RequestMapping("email")
    public Object emailCaptcha(UserVo userVo) {
        Random random = new Random();
        int capt = random.nextInt(900000) + 100000;
        String captcha = String.valueOf(capt);
        try {
            HtmlEmail email = new HtmlEmail();//能发邮箱的一个对象
            email.setHostName("smtp.qq.com");//设置邮件服务器的名称。这里是发件人的邮箱服务器；比如你用qq邮箱，那就是smtp.qq.cm；126邮箱为smtp.126.com,163邮箱为163.smtp.com
            email.setCharset("UTF-8");
            email.addTo(userVo.getEmail());// 收件人的邮箱地址
            email.setFrom("319602804@qq.com", "房屋租赁系统");//此处填发件人邮箱地址和用户名,用户名可以任意填写
            email.setAuthentication("319602804@qq.com", "sitvqqavnhtvbhab");//发件人的邮箱地址 和 发件人的授权码；这个授权码是需要发件人提前开通和生成的
            //此处填写邮箱地址和客户端授权码
            email.setSubject("邮箱验证");//此处填写邮件主题
            email.setMsg("尊敬的用户您好,您正在进行找回密码操作，验证码是:" + captcha + "。(验证码告知他人将导致账号被盗，请勿泄露)");//设置邮件正文
            email.send();
            userVo.setCaptcha(captcha);
            return Result.builder().code(0).data(userVo).build();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.builder().code(500).build();
        }
    }

    //找回密码
    @RequestMapping("forget")
    public Object forget(UserVo userVo) {
        Result result = userService.forget(userVo);
        return result;
    }

    //查询菜单
    @RequestMapping("menu")
    public Object userMenu(HttpSession session) {
        User user = (User) session.getAttribute("user");
        Result result = userService.selectMenu(user);
        return result;
    }

    //根据条件查询查询用户信息
    @RequestMapping("userInfos")
    public Object userInfos(UserVo userVo) {
        Result result = userService.selectUserInfos(userVo);
        return result;
    }

    //根据用户id更改用户信息
    @RequestMapping("updateuser")
    public Object updateUser(User user, HttpSession session) {
        Result result = userService.updateUser(user);
        session.setAttribute("user", result.getData());
        return result;
    }

    //根据id修改用户密码
    @RequestMapping("updatepwd")
    public Object updatePwd(UserVo userVo, HttpSession session) {
        User usr = (User) session.getAttribute("user");
        Result result = userService.updatePwd(userVo, usr);
        return result;
    }

    //修改头像
    @RequestMapping("updateUserImg")
    public Object updateUserImg(HttpSession session, MultipartFile file) {
        String imgUrl = "F:\\project\\ideaprojects\\houseRentSys\\src\\main\\webapp\\static\\images\\userimgs";
        User user = (User) session.getAttribute("user");
        //文件上传
        if (!file.isEmpty()) {
            //获取上传文件的真实名字
            String originalFilename = file.getOriginalFilename();
            String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileUploadName = uuid.concat("." + filenameExtension);
            if (user.getUuidName() != null) {
                new File(imgUrl, user.getUuidName()).delete();
            }
            user.setUuidName(fileUploadName);
            File file1 = new File(imgUrl, fileUploadName);
            try {
                file.transferTo(file1);
                int line = userService.updateUserImg(user);
                if (line > 0) {
                    return Result.builder().code(0).msg("修改成功！").build();
                } else {
                    return Result.builder().code(500).msg("修改失败！").build();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return Result.builder().code(500).msg("修改失败！").build();
            }
        } else {
            return Result.builder().code(500).msg("未选择文件！").build();
        }
    }

    //用户管理  添加用户
    @RequestMapping("adduser")
    public Object addUser(UserVo userVo) {
        Result result = userService.addUser(userVo);
        return result;
    }

    //用户管理  删除用户  批量删除用户
    @RequestMapping("deluser")
    public Object delUser(UserVo userVo) {
        Result result = userService.delUser(userVo);
        return result;
    }

    //用户管理  重置用户密码
    @RequestMapping("resetuser")
    public Object resetUser(UserVo userVo) {
        Result result = userService.resetUser(userVo);
        return result;
    }

    //    测试500错误
    @RequestMapping("test500")
    public Object test500(UserVo userVo) {
        return 1 / 0;
    } //    测试500错误

}
